'''
Created on 2014-4-21

@author: ASUS
'''
# -*- coding: utf-8 -*-

from __builtin__ import len, file, str, int
from _ast import For
import datetime
import json
import string
import urllib

from numpy import size

from ASIN import get_ASIN
from fetch_info_to_file.get_category import Category
import matplotlib.pyplot as plt
import numpy as np


class Review_Stuff():
    category='Clothing & Accessories>Baby>Baby Girls'

    def category_name(self):

        #return 'Clothing $ Accessories>Women>Jeans'
        #return 'Cell Phones $ Accessories>Cell Phones>Contract Cell Phones'

#    return 'Clothing $ Accessories>Women>Jeans'
        return self.category

  
    def getASIN(self): 
        l = []
        asin=get_ASIN()
        for page in range(0, 28):
            g = asin.write_info(self.category_name(),page)
            l.extend(g)
        return l   
    
    def getASINNumber(self):  
        l = []
        asin=get_ASIN()
        for page in range(0, 28):
            g = asin.write_info(self.category_name(),page)
            l.extend(g)
        return len(l)
    
    def get_product_data(self,info):  
        target_url = 'http://112.124.1.3:8004/api/commodity/' + info + '/'
        return json.loads(urllib.urlopen(target_url).read())

    def review_hist(self,info): 
        product_data = self.get_product_data(info)
        star_list = [float(single_review['star'].split()[0]) \
                 for single_review in product_data['review']]

        plt.hist(star_list, color='grey', align='mid', bins=5, rwidth=0.5)

        plt.show()

    def getReviewInfo(self,info,flie_name):  
        product_data = self.get_product_data(info)
        Asin = product_data['ASIN']
        avg_rank = product_data['stats_info']['avg_info']
        review_count = product_data['stats_info']['review_count']
        single_reviews = []

        file=open(r'../txt_package/'+flie_name+'.txt','a')
        for number in range(0, review_count):
            
            publish_time=product_data['review'][number]['publishTime']
            rank=product_data['review'][number]['star']
            keyword=product_data['review'][number]['summary']
            single_reviews.append({'time':publish_time,'rank':rank,'keyword':keyword})                      
        review = {'ASIN': Asin, 'avg_rank': avg_rank,
               'review_count': review_count, 'single_review':single_reviews}
        review_str=str(review)

            
        file.write(review_str)
        file.write('\n')

        #f=open(r'../txt_package/women_jeans_review_count.txt','a')
       # print Asin+'  '+str(review_count)
        #f.write(str(review_count))

       # f.close()
        file.close()
        
  
    def readFromLocal(self,file_name):
        f=open(r'../txt_package/'+file_name+'.txt','r')
        l=[]
        line = f.readline()
        while line:
            info=eval(line)
            l.append(info)
            line = f.readline()
        f.close()
        return l
    

    def review_count_hist(self):
        file = open(r'../txt_package/phone_review_count.txt','r')
        l=[]
        count_1 = 0
        count_2 = 0
        count_3 = 0
        count_4 = 0
        count_5 = 0
        for number in range(0,559):

            line=file.readline()
            print line
            count = string.atoi(line)
            if count==0:
                count_1 = count_1+1
            elif count<30:
                count_2 = count_2+1
            elif count<100:
                count_3 = count_3+1
            elif count<300:
                count_4 = count_4+1
            else:
                count_5 = count_5+1
        
        plt.xlabel(u'review_count_range')
        plt.ylabel(u'product_count')
        plt.xticks((2,12,22,32,42),(u'0',u'1-30',u'30-100',u'100-300',u'300-700'))
        rect = plt.bar(left=(2,12,22,32,42), height=(count_1,count_2,count_3,count_4,count_5), width=8,align="center")
        self.autolabel(rect)
        plt.show()
               
    def autolabel(self,rects):
        for rect in rects:
            height = rect.get_height()
            plt.text(rect.get_x()+rect.get_width()/2., 1.01*height, '%s' % int(height)) 
            
    def product_line_chart(self):
        #women jeans
        #no reduce price
        asin1 = 'B00A2XMCKQ'
        asin2 = 'B007UM6P32'
        asin3 = 'B005DMF8OS'
        #reduce price
        asin4 = 'B005FKUZM8'
        asin5 = 'B002DUCUBM'
        #rise price
        asin6 = 'B00801T70K'
        asin7 = 'B007U46U2G'
        #phone
        #no reduce price
        asin8 = 'B00E6FG5I6'
        asin9 = 'B00F2SN53Y'
        asin10= 'B00F2SKPIM'
        #reduce price
        asin11= 'B0097MVKW4'
        asin12= 'B00CRNWKF6'
        #rise price
        asin13= 'B008HTJLF6'
        asin14= 'B00FJ8WBJG'
        review = self.single_review(asin10)
        ylist = []
        xlist = []
        tempi = 1
        firstreview = str(review[0]['publishTime']).split(' ')
        firsttime = str(firstreview[0]).split('-')
        tempdate = datetime.datetime(int(firsttime[0]),int(firsttime[1]),int(firsttime[2]));
        for i in range(1,len(review)-30):
            temp = str(review[i]['publishTime']).split(' ')
            publishTime = str(temp[0]).split('-')
            year = int(publishTime[0])
            month = int(publishTime[1])
            date = int(publishTime[2])
            print review[i]['publishTime']
            if tempdate.__eq__(datetime.datetime(year,month,date)):
                tempi = tempi+1
            else:
                if(tempi!=0): 
                    xlist.append(tempi)
                    ylist.append(tempdate)
                    tempi = 1
            tempdate = datetime.datetime(year,month,date)
        plt.plot(ylist,xlist,'o--')
        plt.plot(datetime.datetime(2013,11,23),0)
        plt.plot(datetime.datetime(2014,3,9),1.4,'r',marker='*')
        plt.plot(datetime.datetime(2013,11,23),5)
        plt.figtext(0.1,0.92,'red point represent reduce price time',color='green')
        plt.show()
        
    def single_review(self,asin):
        product = self.get_product_data(asin)
        review = product['review']
        return review
       

    def get_review_counts_average_rank(self,fileName):
        l=self.readFromLocal(fileName)
        review_counts_rank=[]
        for single in l:
            asin_review_count_rank={'ASIN':single['ASIN'],'review_count':single['review_count'],'avg_rank':single['avg_rank']}
            review_counts_rank.append(asin_review_count_rank)
        return review_counts_rank
    
    def setCategory(self,name):
        self.category=name
     

    
    def download_all_review_stuff(self,file_name):
        for single_asin in self.getASIN():
            self.getReviewInfo(single_asin,file_name)
            

                
if __name__ == '__main__':
    R=Review_Stuff()
    asins = R.getASIN()
    for i in range(0,len(asins)):
        R.getReviewInfo(asins[i], 'baby_clothes_review')
        
    
   
    #R.draw_review_bar(l)
